﻿using Microsoft.AspNetCore.Builder;
using NConsul;
using System;
using System.Threading.Tasks;

namespace MicService.GrpcServer
{
    public static class NConsulHelper
    {
        public static async Task UseGRPCConsul(this IApplicationBuilder app, ConsulConfigModel consulConfigModel, HealConfigMol healConfigMol)
        {
            using ConsulClient nconsulClient = new ConsulClient(c =>
            {
                c.Address = new Uri($"http://{consulConfigModel.IP}:{consulConfigModel.Port}");
                c.Datacenter = "dc1";
            });

            await nconsulClient.Agent.ServiceRegister(new AgentServiceRegistration()
            {
                ID = "grpcserviceID" + healConfigMol.IP + ":" + healConfigMol.CheckPort,
                Name = healConfigMol.GroupName,
                Address = healConfigMol.IP,
                Port = healConfigMol.CheckPort,
                Tags = healConfigMol.Tag,
                Check = new AgentServiceCheck() 
                {
                    Interval = TimeSpan.FromSeconds(12),
                    Timeout = TimeSpan.FromSeconds(5),
                    DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(20),
                    GRPC = $"{healConfigMol.IP}:{ healConfigMol.CheckPort}",
                    GRPCUseTLS = false
                }
            });
        }
    }
}